#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Simple command-line example for adexchangebuyer API.

Command-line application that exercises the adexchangebuyer API.

Usage:
  $ python sample.py

You can also get help on all the command-line flags the program understands
by running:

  $ python sample.py --help

To get detailed log output run:

  $ python sample.py --logging_level=DEBUG
"""

__author__ = 'myl@google.com (Matthew Young-Lai)'

import gflags
import httplib2
import logging
import sys

from apiclient.errors import HttpError
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

FLAGS = gflags.FLAGS

# The gflags module makes defining command-line options easy for
# applications. Run this program with the '--help' argument to see
# all the flags that it understands.
gflags.DEFINE_enum('logging_level', 'ERROR',
                   ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                   'Set the level of logging detail.')

gflags.DEFINE_string('client_id', None,
                     'The client ID that you created for this application at '
                     'code.google.com/apis/console')

gflags.DEFINE_string('client_secret', None,
                     'The "client secret" value that corresponds to the '
                     'application specified in client_id.')

gflags.DEFINE_string('cookie_matching_url', None,
                     'The cookie matching url to set in the account '
                     'configuration.')


def main(argv):
  # Let the gflags module process the command-line arguments
  try:
    argv = FLAGS(argv)
  except gflags.FlagsError, e:
    print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
    sys.exit(1)

  # Set the logging according to the command-line flag
  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))

  # If the Credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # Credentials will get written back to a file.
  storage = Storage('sample.dat')
  credentials = storage.get()

  # Set up a Flow object to be used if we need to authenticate. This
  # sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
  # the information it needs to authenticate. Note that it is called
  # the Web Server Flow, but it can also handle the flow for native
  # applications <http://code.google.com/apis/accounts/docs/OAuth2.html#IA>
  # The client_id client_secret are copied from the API Access tab on
  # the Google APIs Console <http://code.google.com/apis/console>. When
  # creating credentials for this application be sure to choose an Application
  # type of "Installed application".
  flow = OAuth2WebServerFlow(
      client_id=FLAGS.client_id,
      client_secret=FLAGS.client_secret,
      scope='https://www.googleapis.com/auth/adexchange.buyer',
      user_agent='adexchangebuyer-cmdline-sample/1.0')

  if credentials is None or credentials.invalid:
    credentials = run(flow, storage)

  # Create an httplib2.Http object to handle our HTTP requests and authorize it
  # with our good Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build('adexchangebuyer', 'v1', http=http)

  try:
    #################################################
    ###   Interact with the accounts resource.    ###
    #################################################
    # Execute an accounts "list" operation.
    account_list_request = service.accounts().list()
    account_list_response = account_list_request.execute()
    print '\nAccounts List response:'
    print account_list_response

    # If there were accounts in the result of the "list" operation, then execute
    # a "get" and then an "update" on the first account in the list.
    if account_list_response['items']:

      # Find the account id of the first account in the list.
      account_id = account_list_response['items'][0]['id']

      # Execute a "get" operation for the account id.
      account_get_request = service.accounts().get(id=account_id)
      account_get_response = account_get_request.execute()
      print '\nAccounts Get response:'
      print account_get_response

      # Start from the configuration returned by the "get" operation, and change
      # the cookieMatchingUrl to the value passed in FLAGS.cookie_matching_url
      update_body = account_get_response
      if FLAGS.cookie_matching_url:
        update_body['cookieMatchingUrl'] = FLAGS.cookie_matching_url

      # Execute an "update" operation for the account.
      account_update_request = service.accounts().update(
          id=account_id, body=update_body)
      account_update_response = account_update_request.execute()
      print '\nAccounts Update response:'
      print account_update_response

    #################################################
    ###   Interact with the creatives resource.   ###
    #################################################
    # Submit a new creative.
    creative_body = {
        'accountId': 12345678,
        'adgroupId': 23456789,
        'buyerCreativeId': 'test_creative_1',
        'HTMLSnippet': '<a href="http://www.google.com">Hi there!</a>',
        'clickThroughUrl': ['http://www.google.com'],
        'width': 300,
        'height': 250,
        'advertiserName': 'google',
    }
    creative_submit_request = service.creatives().insert(body=creative_body)

    creative_submit_response = creative_submit_request.execute()
    print '\nInsert response:'
    print creative_submit_response

    ###################################################
    ###   Interact with the directdeals resource.   ###
    ###################################################
    # Execute a direct deals "list" operation.
    direct_deals_list_request = service.directDeals().list()
    direct_deals_list_response = direct_deals_list_request.execute()
    print '\nDirect Deals List response:'
    print direct_deals_list_response

    # We can also query for a specific direct deal by id. If there were any
    # listed in our list request we'll pick the first one to query directly.
    if direct_deals_list_response['direct_deals']:

      # Find the direct deal id of the first direct deal in the list.
      direct_deal_id = direct_deals_list_response['direct_deals'][0]['id']

      # Execute a "get" operation for the direct deal id.
      direct_deals_get_request = service.directDeals().get(id=direct_deal_id)
      direct_deals_get_response = direct_deals_get_request.execute()
      print '\nDirect Deals Get Response:'
      print direct_deals_get_response

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run '
           'the application to re-authorize')
  except HttpError as e:
    print e

if __name__ == '__main__':
  main(sys.argv)
